package org.smart4j.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * Created by Wangminze on 2016/12/17.
 * Description: 流操作工具类
 */
public final class StreamUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtil.class);

    /**
     * author: Wangminze
     * date: 2016/12/17
     * description: 从输入流中获取字符串
     *
     * @param inputStream
     * @return
     */
    public static String getString(InputStream inputStream) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception e) {
            LOGGER.error("Get String failure", e);
            throw new RuntimeException(e);
        }
        return stringBuilder.toString();
    }

    /**
     * Description : 将输入流复制到输出流
     * @antuor : Wangminze
     * @version : 2016/12/26
     * @param :
     * @return :
     **/
    public static void copyStream(InputStream inputStream, OutputStream outputStream){
        try{
            int length;
            byte[] buffer = new byte[4 * 1024];
            while ((length = inputStream.read(buffer, 0, buffer.length)) != -1){
               outputStream.write(buffer, 0, length);
            }
            outputStream.flush();
        }catch (Exception e){
            LOGGER.error("Copy stream failure", e);
            throw new RuntimeException(e);
        }finally {
            try {
                inputStream.close();
                outputStream.close();
            }catch (Exception e){
                LOGGER.error("Close stream failure", e);
            }
        }
    }

}
